import PropTypes from 'prop-types';
import React from 'react';
import {getAuthority} from './authority';

const check = (authority, currentAuthority, Exception) => {
    // 没有判定权限.默认查看所有
    // Retirement authority, return true;
    if (!authority) {
        return true;
    }
    // 数组处理
    if (Array.isArray(authority)) {
        if (authority.indexOf(currentAuthority) >= 0) {
            return true;
        }
        return Exception;
    }

    // string 处理
    if (typeof authority === 'string') {
        if (authority === currentAuthority) {
            return true;
        }
        return Exception;
    }

    // Function 处理
    if (typeof authority === 'function') {
        try {
            const bool = authority(currentAuthority);
            if (bool) {
                return true;
            }
            return Exception;
        } catch (error) {
            throw error;
        }
    }
    throw new Error('unsupported parameters');
};

const hasPermissions = (authority, Exception) => {

    return check(authority, getAuthority(), Exception);
};

const authorizedWrap = (ComposedComponent) => class AuthorizedWrap extends React.Component {

    static propTypes = {
        authority: PropTypes.string.isRequired,
    };

    render() {

        if (hasPermissions(this.props.authority)) {
            return <ComposedComponent  {...this.props} />;
        } else {
            return null;
        }
    }
};

export default authorizedWrap;